package org.example.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.example.service.TranslationService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 百度翻译API实现
 */
@Service
@Slf4j
public class BaiduTranslationService implements TranslationService {

    @Value("${baidu.translate.appid}")
    private String appId;

    @Value("${baidu.translate.secret-key}")
    private String secretKey;

    @Value("${baidu.translate.url}")
    private String apiUrl;

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    private final Random random;

    public BaiduTranslationService() {
        this.restTemplate = new RestTemplate();
        this.objectMapper = new ObjectMapper();
        this.random = new Random();
    }

    @Override
    public String translateEnToZh(String word) {
        if (word == null || word.trim().isEmpty()) {
            return "";
        }

        try {
            // 生成随机数作为salt
            String salt = String.valueOf(random.nextInt(10000));

            // 计算签名: appid+q+salt+密钥
            String sign = generateMD5(appId + word + salt + secretKey);

            // 构建请求URL
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl)
                    .queryParam("q", word)
                    .queryParam("from", "en")
                    .queryParam("to", "zh")
                    .queryParam("appid", appId)
                    .queryParam("salt", salt)
                    .queryParam("sign", sign);

            log.debug("调用百度翻译API，URL: {}", builder.toUriString());

            // 发送请求
            ResponseEntity<String> response = restTemplate.getForEntity(
                    builder.toUriString(), String.class);

            // 解析响应
            JsonNode root = objectMapper.readTree(response.getBody());

            // 检查是否有错误
            if (root.has("error_code")) {
                String errorCode = root.get("error_code").asText();
                String errorMsg = root.get("error_msg").asText();
                log.error("百度翻译API返回错误: code={}, msg={}", errorCode, errorMsg);
                return "翻译失败: " + errorMsg;
            }

            // 提取翻译结果
            if (root.has("trans_result") && root.get("trans_result").isArray() &&
                    root.get("trans_result").size() > 0) {
                return root.get("trans_result").get(0).get("dst").asText();
            }

            return "无法获取翻译结果";
        } catch (Exception e) {
            log.error("调用百度翻译API失败", e);
            return "翻译服务异常: " + e.getMessage();
        }
    }

    /**
     * 生成MD5签名
     */
    private String generateMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("MD5加密失败", e);
            throw new RuntimeException("MD5加密失败", e);
        }
    }
}
